package com.kly.user.task;

import cn.hutool.core.net.NetUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.HttpUtil;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.google.common.collect.Maps;
import com.google.common.eventbus.AsyncEventBus;
import com.kly.enums.ParameterTypeEnum;
import com.kly.user.chatterService.ChatService;
import com.kly.user.db.dao.*;
import com.kly.user.db.entity.IssueSupplyRecordEntity;
import com.kly.user.db.entity.UserGreetingCommonContentEntity;
import com.kly.user.dto.AddWlmReq;
import com.kly.user.dto.chatter.request.ConversationReq;
import com.kly.user.enums.AppEnum;
import com.kly.user.enums.OnlineStatus;
import com.kly.user.eventbus.ActionEnum;
import com.kly.user.eventbus.Event;
import com.kly.user.serviceImpl.OtherServiceImpl;
import com.kly.user.serviceImpl.WlmServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

/**
 * chatter 下发补给
 */
@Component
public class SupplyIssueTask {

    private static Log logger = LogFactory.getLog(SupplyIssueTask.class);

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserChatterMappingDao userChatterMappingDao;

    @Resource
    private AsyncEventBus pushEventBus;

    @Autowired
    private OtherServiceImpl otherService;

    @Autowired
    private WlmServiceImpl wlmService;

    @Resource
    private ChatService chatService;

    @Resource
    private UserGreetingCommonContentDao userGreetingCommonContentDao;

    @Autowired
    private IssueSupplyRecordDao issueSupplyRecordDao;

    @Autowired
    private IssueSupplyUserDao issueSupplyUserDao;

    @NacosValue(value = "${send.flashchat.url:http://localhost:9104/api/im/message/sendMsg}", autoRefreshed = true)
    private String sendFlashchatUrl;


    @NacosValue(value = "${task.job.executor.ip}", autoRefreshed = true)
    private String taskJobExecutor;

    private String localIP = NetUtil.getLocalhostStr();

//    @Scheduled(fixedDelay = 60000 * 5)
//    @Scheduled(fixedDelay = 5000)
    public void execute() {

        if (!taskJobExecutor.contains(localIP)) {
            logger.info("=============NotTaskJobExecutor, currentLocalAddress:{}, onlyExecuteTaskIn:{}", localIP, taskJobExecutor);
            return;
        }

        //读取所有在线chatter 按等级排序
        List<String> chatterCodeList = userDao.getOnlineChatterCode();
        for (String chatterCode : chatterCodeList) {

            //读取整点时间
            LocalDateTime currentHourTime = LocalDateTime.now().withMinute(0).withSecond(0).withNano(0);
            int issueCountHour = issueSupplyRecordDao.issueCountHour(chatterCode, currentHourTime);
            if (issueCountHour < 10) {
                //过滤 wlm lk 首页 建联的
                List<String> modelCodeList = userChatterMappingDao.selectAll(chatterCode);
                for (String modelCode : modelCodeList) {
                    //判断是否与user有关系
                    String userCode = userDao.querySupplyRecommendUsers(modelCode);
                    if (StringUtils.isNotEmpty(userCode)) {
                        //发送flash chat消息
                        send(chatterCode, userCode, modelCode);
                        return;
                    }
                }
            }
        }

        //读取在线用户并进行过滤
        //每10分钟进行下发
        //发送招呼语 flashchat标识
        //记录下发状态，记录下发是否成功 失败原因
    }


    private void send(String chatterCode, String userCode, String friendUserCode) {
        final String sendMsgs = getCommonGreeting();
        if (StringUtils.isEmpty(sendMsgs)) {
            addRecord(chatterCode, friendUserCode, userCode, 0, "无问候语");
            return;
        }

        final JSONObject params = new JSONObject();
        params.put("toUserCode", userCode);
        params.put("fromUserCode", friendUserCode);
        params.put("content", sendMsgs);
        params.put("source", "supplyIssueTask");

        final HashMap<String, String> header = Maps.newHashMap();
        header.put("accept", "application/json");
        header.put("content-type", "application/json");
        final String result = HttpUtil.postPageBody(sendFlashchatUrl, header, params.toJSONString());
        if (StringUtils.isEmpty(result)) {
            addRecord(chatterCode, friendUserCode, userCode, 0, "下发补给失败");
            return;
        }
        final JSONObject resultJson = JSONObject.parseObject(result);
        final int code = resultJson.getIntValue("code");
        if (code != 0) {
            addRecord(chatterCode, friendUserCode, userCode, 0, "下发补给失败");
            return;
        }
        //发送通知
        if (otherService.pushNotification(userCode, 1).isSuccess()) {
            //建联
            AddWlmReq addWlmReq = new AddWlmReq();
            addWlmReq.setUserCode(friendUserCode);
            addWlmReq.setUserCodeFriend(userCode);
            try {
                wlmService.timeFlashChat(addWlmReq);
            } catch (Exception e) {
                addRecord(chatterCode, friendUserCode, userCode, 0, "下发补给失败");
                return;
            }
            // 增加会话关系
            final ConversationReq conversationReq = ConversationReq.builder().fromUserCode(friendUserCode).toUserCode(userCode)
                    .type(1).source(AppEnum.MECHAT.getAppCode()).latestTime(new Date()).latestMsg(sendMsgs).conversationType(1).build();
            chatService.storageConversation(conversationReq);
            pushMessage(friendUserCode, userCode, "S20005");
            addRecord(chatterCode, friendUserCode, userCode, 1, "下发补给成功");
            issueSupplyUserDao.updateConnectCount(userCode);
        }
    }

    private String getCommonGreeting() {
        final HashMap<String, Object> params = Maps.newHashMap();
        params.put("deleted", 0);
        params.put("greetingCode", 121);
        final List<UserGreetingCommonContentEntity> userGreetingCommonContentEntities = userGreetingCommonContentDao.selectByParams(params);
        if (CollectionUtils.isEmpty(userGreetingCommonContentEntities)) {
            return null;
        }
        Random random = new Random();
        int n = random.nextInt(userGreetingCommonContentEntities.size());
        return userGreetingCommonContentEntities.get(n).getGreetingContent();
    }

    private void pushMessage(String fromUseCode, String toUserCode, String target) {
        pushEventBus.post(buildEvent(fromUseCode, toUserCode, target));
    }

    private Event buildEvent(String fromUseCode, String toUserCode, String target) {
        Map<String, Object> params = Maps.newHashMap();
        params.put("type", ParameterTypeEnum.PUSH_MODEL_ONLINE.getId());
        params.put("target", target);
        params.put("online", OnlineStatus.ONLINE_STATUS.getType());
        params.put("flashchatFlag", 1);
        return Event.builder().eventActionEnum(ActionEnum.PUSH_MSG).fromUserCode(fromUseCode).toUserCode(toUserCode).app(AppEnum.MEBOO).content(JSONObject.toJSONString(params)).build();
    }


    private void addRecord(String chatterCode, String modelCode, String userCode, int resultStatus, String describe) {
        IssueSupplyRecordEntity issueSupplyRecordEntity = new IssueSupplyRecordEntity();
        issueSupplyRecordEntity.setChatterCode(chatterCode);
        issueSupplyRecordEntity.setModelCode(modelCode);
        issueSupplyRecordEntity.setUserCode(userCode);
        issueSupplyRecordEntity.setResultStatus(resultStatus);
        issueSupplyRecordEntity.setMark(describe);
        issueSupplyRecordDao.insert(issueSupplyRecordEntity);
    }
}
